<template>
  <view class="container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <input type="text" placeholder="请输入搜索关键词" v-model="searchQuery" @confirm="onSearch" />
    </view>

    <!-- 布局容器 -->
    <view class="layout">
      <!-- 宠物类型列表（侧边栏） -->
      <view class="category-list">
        <view 
          v-for="(type, index) in petTypes" 
          :key="type.id" 
          :class="['category-item', { active: activeType === index }]" 
          @click="selectType(index)"
        >
          {{ type.name }}
        </view>
      </view>

      <!-- 商品展示 -->
      <view class="product-list">
        <view 
          v-for="(product, index) in products" 
          :key="product.id" 
          class="product-item card"
          @click="toProductDetails(product.id)"
        >
          <image :src="product.img" class="product-image" />
          <view class="product-details">
            <text class="product-name">{{ product.name }}</text>
            <view class="product-prices">
              <view class="price-container">
                <text v-if="product.discount_price" class="product-discount-price">￥{{ product.discount_price }}</text>
                <text class="product-original-price" v-if="product.discount_price">￥{{ product.original_price }}</text>
                <text v-else class="product-original-price2">￥{{ product.original_price }}</text>
              </view>
              <view class="cart-container">
                <image v-if="product.state === '有库存'" src="/static/icon/gouwuche-copy.png" class="icon-gouwuche" @click.stop="addToCart(product)"></image>
                <image v-else src="/static/icon/gouwuche.png" class="icon-gouwuche-disabled" @click.stop="addToCart(product)"></image>
              </view>
            </view>
          </view>
        </view>
        <view class="no-more">没有更多啦</view>
      </view>
    </view>

    <!-- 对话框背景遮罩 -->
    <view v-if="isDialogVisible" class="mask" @click="closeDialog"></view>

    <!-- 对话框 -->
    <view v-if="isDialogVisible" class="dialog">
      <view class="dialog-content">
        <view class="product-info">
          <image :src="cartDialogProduct.img" class="product-image" />
          <view class="product-details">
            <text class="product-name">{{ cartDialogProduct.name }}</text>
            <view class="product-prices2">
				<text v-if="cartDialogProduct.discount_price" class="product-discount-price">￥{{ cartDialogProduct.discount_price }}</text>
              <text class="product-original-price" v-if="cartDialogProduct.discount_price">￥{{ cartDialogProduct.original_price }}</text>
              <text v-else class="product-original-price2">￥{{ cartDialogProduct.original_price }}</text>
              
            </view>
          </view>
        </view>
        <view class="quantity-control">
          <button @click="decreaseQuantity">-</button>
          <view>{{ cartDialogProduct.quantity }}</view>
          <button @click="increaseQuantity">+</button>
        </view>
        <button @click="addProductToCart" class="add-to-cart-button">添加到购物车</button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      searchQuery: '',
      petTypes: [],
      products: [],
      activeType: 0,
      isDialogVisible: false,
      cartDialogProduct: { quantity: 1 }, 
    };
  },
  methods: {
    onSearch() {
      if (this.searchQuery.trim() !== '') {
        this.fetchProducts(this.searchQuery);
      }
    },
   fetchPetTypes() {
     uni.request({
       url: 'http://localhost:8887/Pettype/findAll',
       success: (res) => {
         if (res.data && res.data.code === 200 && res.data.data) {
           this.petTypes = res.data.data;
           // console.log(this.petTypes);
           this.selectType(0); // 加载第一个宠物类型的商品数据
         } else {
           console.error('数据格式不正确或请求失败');
           uni.showToast({
             title: '请求宠物类型数据失败',
             icon: 'none',
             duration: 2000
           });
         }
       },
       fail: () => {
         console.error('请求宠物类型数据失败');
         uni.showToast({
           title: '请求宠物类型数据失败',
           icon: 'none',
           duration: 2000
         });
       }
     });
   },
    fetchProducts(name) {
      uni.request({
        url: `http://localhost:8887/Product/selectname?name=${encodeURIComponent(name)}`,
        success: (res) => {
          if (res.data && res.data.data && res.data.data.length > 0) {
            this.products = res.data.data;
			// console.log(this.products);
          } else {
            this.products = [];
            uni.showToast({
              title: '没有找到相关商品',
              icon: 'none',
              duration: 2000
            });
          }
        },
        fail: () => {
          console.error('请求商品数据失败');
          this.products = [];
          uni.showToast({
            title: '请求商品数据失败',
            icon: 'none',
            duration: 2000
          });
        }
      });
    },
  selectType(index) {
    this.activeType = index;
    const type = this.petTypes[index];
    uni.request({
      url: `http://localhost:8887/Product/selectpettype_id?pettype_id=${encodeURIComponent(type.id)}`,
      success: (res) => {
        if (res.data && res.data.code === 200 && res.data.data) {
          this.products = res.data.data;
          // console.log(this.products);
        } else {
          this.products = [];
          uni.showToast({
            title: '没有找到相关商品',
            icon: 'none',
            duration: 2000
          });
        }
      },
      fail: () => {
        console.error('请求宠物类型商品数据失败');
        this.products = [];
        uni.showToast({
          title: '请求宠物类型商品数据失败',
          icon: 'none',
          duration: 2000
        });
      }
    });
  },
    addToCart(product) {
      if (product.state === "无库存") {
        uni.showToast({
          title: '该商品无库存',
          icon: 'none',
          duration: 2000
        });
      } else {
        this.cartDialogProduct = { ...product, quantity: 1 }; 
        this.isDialogVisible = true;
      }
    },
    addProductToCart() {
      if (this.cartDialogProduct.state === "无库存") {
        uni.showToast({
          title: '该商品无库存',
          icon: 'none',
          duration: 2000
        });
        return;
      }

      const token = uni.getStorageSync('Authorization');
      const data = {
        product_id: this.cartDialogProduct.id,
        quantity: this.cartDialogProduct.quantity,
      };

      const header = {
        'Content-Type': 'application/json',
        'Authorization': token,
      };

      uni.request({
        url: 'http://localhost:8887/Shoppingcart/add', 
        method: 'POST',
        header: header,
        data: data,
        success: (res) => {
          if (res.data.code === 200) {
            this.isDialogVisible = false;
            uni.showToast({
              title: res.data.message,
              icon: 'success',
              duration: 2000
            });
          } else if (res.data.status === 'unauthorized') {
            uni.navigateTo({
              url: '/pages/login/login',
            });
          } else {
            uni.showToast({
              title: res.data.message,
              icon: 'none',
              duration: 2000
            });
          }
        },
        fail: (err) => {
          uni.showToast({
            title: '网络请求失败，请稍后再试',
            icon: 'none',
            duration: 2000
          });
        }
      });
    },
    increaseQuantity() {
      this.cartDialogProduct.quantity++;
    },
    decreaseQuantity() {
      if (this.cartDialogProduct.quantity > 1) {
        this.cartDialogProduct.quantity--;
      }
    },
    closeDialog() {
      this.isDialogVisible = false;
    },
    toProductDetails(productId) {
      uni.navigateTo({
        url: `/pages/productdetails/productdetails?id=${productId}`,
      });
    }
  },
  mounted() {
    this.fetchPetTypes();
  },
};
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  position: relative;
}
.search-bar {
  padding: 10px;
  background-color: #f8f8f8;
  border-bottom: 1px solid #ddd;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: sticky;
  top: 0;
  z-index: 100;
}
.search-bar input {
  flex-grow: 1;
  border: 1px solid #ddd;
 padding: 5px;
 border-radius: 4px;
 }
 
 .layout {
 display: flex;
 height: 100vh;
 }
 .category-list {
 width: 60px;
 background-color: #fff;
 position: sticky;
 top: 10px;
 z-index: 100;
 height: 100%;
 }
 .category-item {
 padding: 10px;
 border-bottom: 1px solid #eee;
 text-align: center;
 }
 .category-item.active {
 background-color: #007aff;
 color: white;
 }
 .product-list {
 flex-grow: 1;
 background-color: #f8f8f8;
 padding: 10px;
 overflow-y: auto;
 padding-bottom: 200px;
 }
 .product-item {
 display: flex;
 align-items: flex-start;
 border: 1px solid #eee;
 border-radius: 8px;
 margin-bottom: 10px;
 padding: 10px;
 background-color: #fff;
 box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
 }
 .product-image {
 width: 90px;
 height: 90px;
 }
 .product-details {
 display: flex;
 flex-direction: column;
 justify-content: space-between;
 width: 100%;
 height: 90px;
 padding-left: 10px;
 }
 .product-name {
 font-size: 16px;
 color: #333;
 font-weight: bold;
 width: 90%;
 display: inline-block;
 vertical-align: top;
 word-wrap: break-word;
 overflow: hidden;
 text-overflow: ellipsis;
 }
 .product-prices {
 display: flex;
 align-items: center;
 justify-content: space-between;
 width: 100%;
 }
 .product-prices2 {
 /* display: flex; */
 align-items: center;
 justify-content: space-between;
 width: 100%;
 }
 .price-container {
 flex-grow: 1;
 }
 .cart-container {
 display: flex;
 align-items: center;
 }
 .product-original-price {
 text-decoration: line-through;
 font-size: 14px;
 color: #999;
 }
 .product-original-price2 {
 font-size: 18px;
 color: #e4393c;
 font-weight: bold;
 }
 .product-discount-price {
 font-size: 18px;
 color: #e4393c;
 font-weight: bold;
 }
 .icon-gouwuche {
 width: 24px;
 height: 24px;
 }
 .icon-gouwuche-disabled {
 width: 24px;
 height: 24px;
 opacity: 0.5;
 /* pointer-events: none; */
 }
 .mask {
 position: fixed;
 top: 0;
 left: 0;
 right: 0;
 bottom: 0;
 background-color: rgba(0, 0, 0, 0.5);
 z-index: 1000;
 }
 .dialog {
 position: fixed;
 bottom: 0;
 left: 0;
 width: 100%;
 background-color: #fff;
 z-index: 1001;
 }
 .dialog-content {
 padding: 20px;
 }
 .product-info {
 display: flex;
 align-items: center;
 margin-bottom: 20px;
 }
 .quantity-control {
 display: flex;
 align-items: center;
 margin-bottom: 20px;
 }
 .quantity-control button {
 margin: 0 10px;
 }
 .add-to-cart-button {
 width: 100%;
 background-color: #e4393c;
 color: white;
 text-align: center;
 padding: 10px;
 border: none;
 outline: none;
 }
 .no-more {
 width: 100%;
 text-align: center;
 margin-top: 20px;
 color: #999;
 font-size: 16px;
 }
 </style>